package cn.wizzer.app.sys.modules.services.impl;

import cn.wizzer.app.crown.modules.models.constant.CrownConstant;
import cn.wizzer.app.sys.modules.models.SysIPTables;
import cn.wizzer.app.sys.modules.models.SysIpApi;
import cn.wizzer.app.sys.modules.services.SysIPTablesService;
import cn.wizzer.framework.base.model.IPRedisConst;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.util.HttpUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.plugins.wkcache.annotation.CacheDefaults;
import org.nutz.plugins.wkcache.annotation.CacheRemoveAll;
import org.nutz.plugins.wkcache.annotation.CacheResult;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@IocBean(args = {"refer:dao"})
@Service(interfaceClass = SysIPTablesService.class)
@CacheDefaults(cacheName = "sys_ip_tables")
public class SysIPTablesServiceImpl extends BaseServiceImpl<SysIPTables> implements SysIPTablesService {
    public SysIPTablesServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private RedisService redisService;

    private static final Log log = Logs.get();


    @Override
    @CacheResult
    public List<String> queryAll() {
        return this.query(Cnd.where("disabled","=",false))
                .stream()
                .map(SysIPTables::getIp)
                .collect(Collectors.toList());
    }

    @Override
    public void add(SysIPTables ip) {
        this.insert(ip);
        this.clearCache();
    }

    @Override
    public void del(String id) {
        this.delete(id);
        this.clearCache();
    }

    @Override
    public void update(SysIPTables ip) {
        this.updateIgnoreNull(ip);
        this.clearCache();
    }

    @Override
    public void check(List<String> codes, int forCount, String website) {
        // 获取访问ip Queue
        Set<String> ips = redisService.zrange(IPRedisConst.IPS, 0, forCount);
        String url,body;
        // 循环100次处理
        for (String ip : ips) {
            try {
                log.info("当前处理ip：" + ip);
                // 发送请求校验
                url = website + ip;
                body = this.sendHttp(url, CrownConstant.RE_TRY_TIMES);
                log.info("请求" + url + "返回的body：" + body);
                if (Strings.isBlank(body)) {
                    continue;
                }
                SysIpApi sysIpApi = JSONObject.parseObject(body, SysIpApi.class);
                if ("success".equals(sysIpApi.getStatus())) {
                    // 如果是禁用地区，入库
                    if (codes.contains(sysIpApi.getCountryCode())) {
                        int count = this.count(Cnd.where("ip", "=", sysIpApi.getQuery()));
                        if (count == 0) {
                            SysIPTables ipTables = new SysIPTables();
                            ipTables.setIp(sysIpApi.getQuery());
                            this.insert(ipTables);
                            this.clearCache();
                        }
                    }
                    // 删除redis中的值
                    redisService.zrem(IPRedisConst.IPS, ip);
                } else {
                    log.error("解析IP异常。url:" + website + ip);
                }
            } catch (ClassCastException e) {
                log.error("解析IP异常。url:" + website + ip + "。具体异常信息：" + e.getMessage());
            }
        }
    }

    private String sendHttp(String url, int reTry) {
        String body = "";
        // 如果是返回数据中countryCode属于codes，入库
        try {
            body = HttpUtil.createRequest()
                    .setUrl(url)
                    .setTimeOut(5000)
                    .send(HttpUtil.HTTP_METHOD.GET)
                    .getBody();
        } catch (IOException e) {
            log.error("请求检测ip失败，URL：" + url + "重试次数剩余：" + reTry);
            log.error("异常具体信息：" + e);
            if (reTry > 1) {
                return this.sendHttp(url, --reTry);
            }
        }
        return body;
    }


    @Override
    @CacheRemoveAll
    public void clearCache() {
    }

}
